package org.cheniy.domain.strategy.service.rule.tree.impl;

import lombok.extern.slf4j.Slf4j;
import org.cheniy.domain.strategy.model.valobj.RuleLogicCheckTypeVO;
import org.cheniy.domain.strategy.model.valobj.StrategyAwardStockKeyVO;
import org.cheniy.domain.strategy.repository.IStrategyRepository;
import org.cheniy.domain.strategy.service.armory.IStrategyDispatch;
import org.cheniy.domain.strategy.service.rule.tree.ILogicTreeNode;
import org.cheniy.domain.strategy.service.rule.tree.factory.DefaultTreeFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @author cheniy
 * @description 抽奖后-删减库存树过滤节点
 * @create 2025/3/8 15:32
 */

@Slf4j
@Component("rule_stock")
public class RuleStockLogicTreeNode implements ILogicTreeNode {


    @Resource
    private IStrategyDispatch iStrategyDispatch;
    @Resource
    private IStrategyRepository iStrategyRepository;
    @Override
    public DefaultTreeFactory.TreeActionEntity logic(String userId, Long strategyId, Integer awardId, String ruleValue, Date endDateTime) {
        log.info("规则过滤-库存扣减 userId:{} strategyId:{} awardId:{} ruleValue:{}",userId, strategyId,awardId,ruleValue);


        // 扣减库存
        Boolean status = iStrategyDispatch.subtractionAwardStock(strategyId, awardId,endDateTime);
        // 扣减成功，则加入到延迟队列中去
        if (status){
            iStrategyRepository.awardStockConsumeSendQueue(StrategyAwardStockKeyVO.builder()
                    .awardId(awardId)
                    .strategyId(strategyId)
                    .build()
            );

            // 并设置返回为拦截-就表示不需要进行下面的节点了，我进行处理了
            return DefaultTreeFactory.TreeActionEntity.builder()
                    .ruleLogicCheckType(RuleLogicCheckTypeVO.TAKE_OVER)
                    .strategyAwardVO(DefaultTreeFactory.StrategyAwardVO.builder()
                            .awardId(awardId)
                            .awardRuleValue("stock")
                            .build())
                    .build();
        }

        return DefaultTreeFactory.TreeActionEntity.builder()
                .ruleLogicCheckType(RuleLogicCheckTypeVO.ALLOW)
                .build();
    }
}
